package imv3.foo.server.handler;

import imv3.protocol.request.MessageRequestPacket;
import imv3.protocol.response.MessageResponsePacket;
import imv3.protocol.session.Session;
import imv3.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019-04-25 22:03
 * 既然选择了远方,便只顾风雨兼程
 */
@ChannelHandler.Sharable
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    public static final MessageRequestHandler INSTANCE = new MessageRequestHandler();

    private MessageRequestHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket request) throws Exception {
        //(1) 拿到消息发送方的会话消息
        Session session = SessionUtil.getSession(ctx.channel());

        //(2) 通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket response = new MessageResponsePacket();

        response.setFromUserId(session.getUserId());
        response.setFromUsername(session.getUsername());
        response.setMessage(request.getMessage());

        //(3) 拿到消息接受方的channel
        Channel toUserChannel = SessionUtil.getChannel(request.getToUserId());

        //(4) 将消息发送给接收方
        if (toUserChannel != null && SessionUtil.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(response);
        } else {
            System.out.println("[" + request.getToUserId() + "]不在线,发送失败");
        }

    }
}
